class Solution {
public:
    vector<int> printMatrix(vector<vector<int> > matrix) {
        if (matrix.size() == 0)
            return {};
        int n = matrix.size();
        int m = matrix[0].size();
        int row = n;
        int col = m;
        vector<int> retnums;
        bool flagright = true;
        bool flagdown = false;
        bool flagleft = false;
        bool flagup = false;
        int x = 0;
        int y = 0;
        int i = 0;
        int j = 0;
        int count = 0;
        int number = n * m;
        while (count < number) {
            count++;
            retnums.push_back(matrix[i][j]);
            if (flagright && j < col)
                j++;
            else if (flagdown && i < row)
                i++;
            else if (flagleft && j > x)
                j--;
            else if (flagup && i > y)
                i--;
            if (flagright && j == col)
            {
                flagdown = !flagdown;
                flagright = !flagright;
                j--;
                i++;
            }
            else if (flagdown && i == row)
            {
                flagdown = !flagdown;
                flagleft = !flagleft;
                i--;
                j--;
            }
            else if (flagleft && j == x)
            {
                flagleft = !flagleft;
                flagup = !flagup;
                col--;
                y++;
            }
            else if (flagup && i == y)
            {
                flagup = !flagup;
                flagright = !flagright;
                row--;
                x++;
            }
        }
        return retnums;
    }
};